home *** CD-ROM | disk | FTP | other *** search
/ C & C++ Multimedia Cyber Classroom / C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso / src / fig06_01.jar / Ch06 / Fig06_01 / Fig06_01.cpp
C/C++ Source or Header  |  1997-10-16  |  1KB  |  56 lines

  1. // Fig. 6.1: fig06_01.cpp
  2. // Create a structure, set its members, and print it.
  3. #include <iostream.h>
  4.  
  5. struct Time {    // structure definition
  6.    int hour;     // 0-23
  7.    int minute;   // 0-59
  8.    int second;   // 0-59
  9. };
  10.  
  11. void printMilitary( const Time & );  // prototype
  12. void printStandard( const Time & );  // prototype
  13.  
  14. int main()
  15. {
  16.    Time dinnerTime;    // variable of new type Time
  17.  
  18.    // set members to valid values
  19.    dinnerTime.hour = 18;
  20.    dinnerTime.minute = 30;
  21.    dinnerTime.second = 0;
  22.  
  23.    cout << "Dinner will be held at ";
  24.    printMilitary( dinnerTime );
  25.    cout << " military time,\nwhich is ";
  26.    printStandard( dinnerTime );
  27.    cout << " standard time.\n";
  28.  
  29.    // set members to invalid values
  30.    dinnerTime.hour = 29;
  31.    dinnerTime.minute = 73;
  32.    
  33.    cout << "\nTime with invalid values: ";
  34.    printMilitary( dinnerTime );
  35.    cout << endl;
  36.    return 0;
  37. }
  38.  
  39. // Print the time in military format
  40. void printMilitary( const Time &t )
  41. {
  42.    cout << ( t.hour < 10 ? "0" : "" ) << t.hour << ":"
  43.         << ( t.minute < 10 ? "0" : "" ) << t.minute;
  44. }
  45.  
  46. // Print the time in standard format
  47. void printStandard( const Time &t )
  48. {
  49.    cout << ( ( t.hour == 0 || t.hour == 12 ) ? 
  50.              12 : t.hour % 12 )
  51.         << ":" << ( t.minute < 10 ? "0" : "" ) << t.minute
  52.         << ":" << ( t.second < 10 ? "0" : "" ) << t.second
  53.         << ( t.hour < 12 ? " AM" : " PM" );
  54. }
  55.  
  56.